namespace PowerManage.Entity.Utils;

/// <summary>
/// 脱敏工具类
/// </summary>
public static class DesensitizationUtil
{
    /// <summary>
    /// 将传入的字符串中间部分字符替换成特殊字符
    /// </summary>
    /// <param name="value">需要脱敏的原始字符串</param>
    /// <param name="startLen">前面保留的字符数量，默认为4</param>
    /// <param name="replaceLen">中间需要替换的字符数量，默认为4</param>
    /// <param name="replaceChar">用于替换的特殊字符，默认为*</param>
    /// <returns>替换后的结果</returns>
    public static string ReplaceWithSpecialChar(this string value, int startLen = 4, int replaceLen = 4,
        char replaceChar = '*')
    {
        //替换长度不可为0 
        if (replaceLen == 0)
        {
            replaceLen = 4;
        }

        //前保留的长度不可大于字内容的长度
        if (value.Length < startLen)
        {
            if (value.Length > replaceLen)
            {
                startLen = value.Length - replaceLen;
            }
        }

        //内容的长度不可小于 前保留+替换的长度
        if (value.Length < startLen + replaceLen)
        {
            replaceLen = value.Length - startLen;
        }

        string startStr = value.Substring(0, startLen);
        string endStr = value.Substring(startLen + replaceLen);
        string specialStr = new string(replaceChar, replaceLen);

        return startStr + specialStr + endStr;
    }

    /// <summary>
    /// 测试脱敏方法
    /// </summary>
    public static void TestDesensitization()
    {
        // 测试手机号脱敏
        string phone = "13812345678";
        string desensitizedPhone = phone.ReplaceWithSpecialChar(3, 4);
        Console.WriteLine($"手机号脱敏: {phone} -> {desensitizedPhone}");

        // 测试邮箱脱敏
        string email = "user@example.com";
        string desensitizedEmail = email.ReplaceWithSpecialChar(2, 3);
        Console.WriteLine($"邮箱脱敏: {email} -> {desensitizedEmail}");

        // 测试身份证号脱敏
        string idCard = "440123199001011234";
        string desensitizedIdCard = idCard.ReplaceWithSpecialChar(6, 8);
        Console.WriteLine($"身份证号脱敏: {idCard} -> {desensitizedIdCard}");

        // 测试短字符串
        string shortStr = "abc";
        string desensitizedShortStr = shortStr.ReplaceWithSpecialChar(1, 1);
        Console.WriteLine($"短字符串脱敏: {shortStr} -> {desensitizedShortStr}");

        // 测试空字符串
        string emptyStr = "";
        string desensitizedEmptyStr = emptyStr.ReplaceWithSpecialChar();
        Console.WriteLine($"空字符串脱敏: '{emptyStr}' -> '{desensitizedEmptyStr}'");
    }
}
